#coding=utf-8
from django.db import models
from django.forms import ModelForm
from django import forms
from django.shortcuts import render_to_response
from django.template import loader, Context
from django.http import HttpResponseRedirect,HttpResponse
from django.http import Http404
from models import type,source,unit,info
from zhaokelai.users.models import users
from zhaokelai.common import skinFolder,checkLogin


##############type###################################################################################
class typeForm(ModelForm):
    class Meta:
        model = type

@checkLogin        
def type_add(request):
    if request.method == 'POST': 
        form = typeForm(request.POST)
        if form.is_valid(): 
            newtype=form.save()
            return HttpResponseRedirect('/customer/type/list') # Redirect after POST
    else:
        form = typeForm() # An unbound form

    return render_to_response(skinFolder(request)+'customer/type_add.html',{
        'form': form,
        'action':'添加',
    })
    
@checkLogin    
def type_modify(request,id):
    if id :
        id=int(id)
        itype = type.objects.get(pk=id)
        if request.method == 'POST': 
            form = typeForm(request.POST, instance=itype)
            ttype=form.save()
            return HttpResponseRedirect('/customer/type/list') # Redirect after POST
        else:
            form = typeForm(instance=itype)
            return render_to_response(skinFolder(request)+'customer/type_add.html',{'form': form,'action':'修改',})
    else:
        raise Http404()

@checkLogin    
def type_delete(request,id=None):
    if id :
        id=int(id)
        itype = type.objects.get(pk=id)
        itype.delete()
    elif request.method == 'POST':       
        ids=request.POST.getlist("tid")
        if ids and len(ids)>0:
            idstring = ','.join(ids)
            type.objects.extra(where=['id IN ('+idstring+')']).delete()
    else:
        pass
    return HttpResponseRedirect('/customer/type/list')
##########source###########################################################################################
class sourceForm(ModelForm):
    class Meta:
        model = source

@checkLogin
def source_add(request):
    if request.method == 'POST': 
        form = sourceForm(request.POST)
        if form.is_valid(): 
            newtype=form.save()
            return HttpResponseRedirect('/customer/source/list') # Redirect after POST
    else:
        form = sourceForm() # An unbound form

    return render_to_response(skinFolder(request)+'customer/source_add.html',{
        'form': form,
        'action':'添加',
    })

@checkLogin    
def source_modify(request,id):
    if id :
        id=int(id)
        itype = source.objects.get(pk=id)
        if request.method == 'POST': 
            form = sourceForm(request.POST, instance=itype)
            ttype=form.save()
            return HttpResponseRedirect('/customer/source/list') # Redirect after POST
        else:
            form = sourceForm(instance=itype)
            return render_to_response(skinFolder(request)+'customer/source_add.html',{'form': form,'action':'修改',})
    else:
        raise Http404()

@checkLogin    
def source_delete(request,id=None):
    if id :
        id=int(id)
        itype = source.objects.get(pk=id)
        itype.delete()
    elif request.method == 'POST':       
        ids=request.POST.getlist("tid")
        if ids and len(ids)>0:
            idstring = ','.join(ids)
            source.objects.extra(where=['id IN ('+idstring+')']).delete()
    else:
        pass
    return HttpResponseRedirect('/customer/source/list')
########unit####################################################################################
class unitForm(ModelForm):
    #def __init__(self, *args, **kwargs):
        #super(unitForm, self).__init__(*args, **kwargs)
        #self.fields['description'].widget = forms.Textarea()
    description = forms.CharField(widget=forms.Textarea(),label='单位介绍',required=False)
    class Meta:
        model = unit

@checkLogin
def unit_add(request):
    if request.method == 'POST': 
        form = unitForm(request.POST)
        if form.is_valid(): 
            newtype=form.save()
            return HttpResponseRedirect('/customer/unit/list') # Redirect after POST
    else:
        form = unitForm() # An unbound form

    return render_to_response(skinFolder(request)+'customer/unit_add.html',{
        'form': form,
        'action':'添加',
    })

@checkLogin    
def unit_modify(request,id):
    if id :
        id=int(id)
        itype = unit.objects.get(pk=id)
        if request.method == 'POST': 
            form = unitForm(request.POST, instance=itype)
            ttype=form.save()
            return HttpResponseRedirect('/customer/unit/list') # Redirect after POST
        else:
            form = unitForm(instance=itype)
            return render_to_response(skinFolder(request)+'customer/unit_add.html',{'form': form,'action':'修改',})
    else:
        raise Http404()

@checkLogin    
def unit_delete(request,id=None):
    if id :
        id=int(id)
        itype = unit.objects.get(pk=id)
        itype.delete()
    elif request.method == 'POST':       
        ids=request.POST.getlist("tid")
        if ids and len(ids)>0:
            idstring = ','.join(ids)
            unit.objects.extra(where=['id IN ('+idstring+')']).delete()
    else:
        pass
    return HttpResponseRedirect('/customer/unit/list')

########customer####################################################################################
class customerForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(customerForm, self).__init__(*args, **kwargs)
        for k in self.fields:
            try:
                self.fields[k].required = False
            except:
                pass
        #self.fields['sex'].widget = forms.RadioSelect()
    sex = forms.ChoiceField(widget=forms.RadioSelect(),label='性别',required=False,choices=(('F', '女士'), ('M', '先生')))
    class Meta:
        model = info
        exclude = ('ower',)

@checkLogin
def customer_add(request):
    if request.method == 'POST': 
        form = customerForm(request.POST)
        if form.is_valid(): 
            newtype=form.save(commit=False)
            newtype.ower=users.objects.get(pk=int(request.session.get('user', None)))
            newtype.save()
            return HttpResponseRedirect('/customer/info/list') # Redirect after POST
    else:
        form = customerForm() # An unbound form

    return render_to_response(skinFolder(request)+'customer/info_add.html',{
        'form': form,
        'action':'添加',
    })

@checkLogin    
def customer_modify(request,id):
    if id :
        id=int(id)
        itype = info.objects.get(pk=id)
        if request.method == 'POST': 
            form = customerForm(request.POST, instance=itype)
            ttype=form.save()
            return HttpResponseRedirect('/customer/info/list') # Redirect after POST
        else:
            form = customerForm(instance=itype)
            return render_to_response(skinFolder(request)+'customer/info_add.html',{'form': form,'action':'修改',})
    else:
        raise Http404()

@checkLogin    
def customer_delete(request,id=None):
    if id :
        id=int(id)
        itype = info.objects.get(pk=id)
        itype.delete()
    elif request.method == 'POST':       
        ids=request.POST.getlist("tid")
        if ids and len(ids)>0:
            idstring = ','.join(ids)
            info.objects.extra(where=['id IN ('+idstring+')']).delete()
    else:
        pass
    return HttpResponseRedirect('/customer/info/list')

def customer_export(request):
    import time
    response = HttpResponse(mimetype='text/csv')
    tstr=time.strftime('%Y-%m-%d_%H%M%S',time.localtime(time.time()))
    response['Content-Disposition'] = 'attachment; filename=customer%s.csv' % tstr
    response['Pragma'] = 'no-cache'
    #response['Content-Type'] = 'text/csv; charset=utf-8'
    t = loader.get_template('customer/csv.html')
    objs = info.objects.all()
    d = []
    d.append(('姓名','性别','年龄','客户类别','客户来源','所属单位','网络帐号','常用网名','办公电话','家庭电话','传真','手机','电子邮件','联系地址','邮政编码','客户代表'))
    for o in objs:
        d.append((o.fullname,o.sex,o.age,o.type,o.source,o.unit, o.account,o.screenname,o.officephone,o.homephone,o.fax,o.mobile,o.email,o.address,o.zipcode,o.ower))
    c = Context({
        'data': d,
    })
    response.write(t.render(c))
    return response

def customer_import(request):
    if request.method == 'POST':
        file_obj = request.FILES.get('file', None)
        fullname_c=request.REQUEST.get("fullname_c", None)
        sex_c=request.REQUEST.get("sex_c", None)
        age_c=request.REQUEST.get("age_c", None)
        type_c=request.REQUEST.get("type_c", None)
        source_c=request.REQUEST.get("source_c", None)
        unit_c=request.REQUEST.get("unit_c", None)
        account_c=request.REQUEST.get("account_c", None)
        screenname_c=request.REQUEST.get("screenname_c", None)
        officephone_c=request.REQUEST.get("officephone_c", None)
        homephone_c=request.REQUEST.get("homephone_c", None)
        fax_c=request.REQUEST.get("fax_c", None)
        mobile_c=request.REQUEST.get("mobile_c", None)
        email_c=request.REQUEST.get("email_c", None)
        address_c=request.REQUEST.get("address_c", None)
        zipcode_c=request.REQUEST.get("zipcode_c", None)
        ower_c=request.REQUEST.get("ower_c", None)
        hul=request.REQUEST.get("hul", None)
        if file_obj:
            import csv
            import StringIO
            buf = StringIO.StringIO(file_obj.read())
            try:
                reader = csv.reader(buf)
            except:
                return render_to_response('permissions.html', {'message':'您需要上传一个CSV（utf-8编码）格式的文件','REFERER':request.META['HTTP_REFERER']})
            i=0
            for row in reader:
                if hul and i==0:
                    i=i+1
                    continue
#                objs = Address.objects.get_list(name__exact=row[0])
                objs = info.objects.filter(fullname=row[int(fullname_c)-1],account=row[int(account_c)-1])
                if not objs:
                    obj = info()
                else:
                    obj = objs[0]
    
                if fullname_c:
                    obj.fullname=row[int(fullname_c)-1]
                if sex_c:
                    tsex=row[int(sex_c)-1]
                    if tsex:
                        obj.sex=tsex
                if age_c:
                    tage=row[int(age_c)-1]
                    if tage and tage!='None':
                        obj.age=int(tage)
                if type_c:
                    type_n=row[int(type_c)-1]
                    type_n=type_n.decode('utf-8')
                    try:
                        itype=type.objects.filter(name=type_n).order_by("-id")[0:1].get()
                    except:
                        itype=type.objects.all().order_by("-id")[0:1].get()
                    obj.type=itype
                if source_c:
                    source_n=row[int(source_c)-1]
                    source_n=source_n.decode('utf-8')
                    try:
                        isource=source.objects.filter(name=source_n).order_by("-id")[0:1].get()
                    except:
                        isource=source.objects.all().order_by("-id")[0:1].get()
                    obj.source=isource
                if unit_c:
                    unit_n=row[int(unit_c)-1]
                    unit_n=unit_n.decode('utf-8')
                    try:
                        iunit=unit.objects.filter(name=unit_n).order_by("-id")[0:1].get()
                    except:
                        iunit=unit.objects.all().order_by("-id")[0:1].get()
                    obj.unit=iunit
                if account_c:
                    tac=row[int(account_c)-1]
                    if tac:
                        obj.account=tac
                if screenname_c:
                    scn=row[int(screenname_c)-1]
                    if scn:
                        obj.screenname=scn 
                if officephone_c:
                    ocp=row[int(officephone_c)-1]
                    if ocp:
                        obj.officephone=ocp
                if homephone_c:
                    hop=row[int(homephone_c)-1]
                    if hop:
                        obj.homephone=hop
                if fax_c:
                    fxt=row[int(fax_c)-1]
                    if fxt:
                        obj.fax=fxt
                if mobile_c:
                    mbt=row[int(mobile_c)-1]
                    if mbt:
                        obj.mobile=mbt
                if email_c:
                    emt=row[int(email_c)-1]
                    if emt:
                        obj.email=emt
                if address_c:
                    adt=row[int(address_c)-1]
                    if adt:
                        obj.address=adt
                if zipcode_c:
                    zct=row[int(zipcode_c)-1]
                    if zct:
                        obj.zipcode=zct
                if ower_c:
                    ower_n=row[int(ower_c)-1]
                    ower_n=ower_n.decode('utf-8')
                    try:
                        iower=users.objects.filter(fullname=ower_n).order_by("-id")[0:1].get()
                    except:
                        iower=users.objects.all().order_by("-id")[0:1].get()
                    obj.ower=iower
                obj.save()
                i=i+1

            return HttpResponseRedirect('/customer/info/list')
        else:
            return render_to_response('permissions.html', {'message':'您需要上传一个CSV（utf-8编码）格式的文件','REFERER':request.META['HTTP_REFERER']})
    else:
        return render_to_response(skinFolder(request)+'customer/import.html')    